package com.mask.im.server.netty.action.handler;

import com.alibaba.fastjson.JSON;
import com.mask.im.server.netty.enums.IMActionEnum;
import com.mask.im.server.netty.model.IMReceiveMessage;
import com.mask.im.server.netty.model.IMSendMessage;
import com.mask.im.server.service.ServiceIdManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author jian
 * @description 心跳操作
 * @date 2025/9/21 08:37
 */
@Log4j2
@Component
public class IMHeartbeatActionHandler extends IMAbstractChatHandler {
    //    im:user:node:
// im:user:node:{userId}:{device} -> nodeId
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public IMActionEnum getAction() {
        return IMActionEnum.HEART_BEAT;
    }

    @Override
    public void handle(IMReceiveMessage imReceiveMessage, Channel channel) {

        IMSendMessage sendInfo = new IMSendMessage();
        sendInfo.setCmd(IMActionEnum.HEART_BEAT.getAction());
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(sendInfo)));

        AttributeKey<Long> attributeKey = AttributeKey.valueOf("USER_ID");
        Long userId = channel.attr(attributeKey).get();
        log.info("netty心跳用户id: {}", userId);
        AttributeKey<Long> heartBeatCount = AttributeKey.valueOf("HEART_BEAT_COUNT");
        Long count = channel.attr(heartBeatCount).get();
        //存放次数
        channel.attr(heartBeatCount).set(++count);
        log.info("netty心跳用户:{},次数:{}", userId, count);
        if (count % 10 == 0) {
            redisTemplate.expire("im:user:node:" + userId + ":default", 800, TimeUnit.SECONDS);
        }
    }
}
